package com.happy016.controller;

import com.happy016.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class UserConsumerController {

    private final Logger logger = LoggerFactory.getLogger(UserConsumerController.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/consumer/user/get/{id}")
    public User getUser(@PathVariable Integer id){
        //User user = restTemplate.getForObject("http://localhost:8686/user/get/"+id,User.class);
        User user = restTemplate.getForObject("http://SERVICE-USER/user/get/"+id,User.class);
        return user;
    }

    /**
     * loadBalancerClient.choose()方法不能与restTemplate.getForObject()写在同一方法,
     * 两者之间有冲突,此时的restTemplate实际上是一个ribbon客户端,已经包含choose行为
     * @author Linyb
     * @since 2017/9/30 9:40
     */
    @GetMapping("/consumer/user/log")
    public void log(){
        ServiceInstance serviceInstance = loadBalancerClient.choose("SERVICE-USER");
        logger.info("{}:{}:{}",serviceInstance.getServiceId(),serviceInstance.getHost(),serviceInstance.getPort());
    }

}
